package com.example.interceptor;

import com.example.exception.TokenException;
import com.example.entity.User;
import com.example.thead.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.example.constant.Constant.TOKEN_USER_ID;

/**
 * @author itheima
 */
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    private RedisTemplate<String, String> redisTemplate;

    //使用构造器来接受SpringMvcSupport的redisTemplate
    public TokenInterceptor(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader(TOKEN_USER_ID);
        if (!StringUtils.hasText(userId)) {
            log.info("userId为空");
            throw new TokenException();
        }
        //封装成user
        User user = new User();
        user.setId(userId);
        //记录登陆者信息，以便后面使用到登陆者信息
        ThreadLocalUtil.set(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //线程结束则清除存放信息
        ThreadLocalUtil.remove();
    }
}
